package com.edfu.core.commons.persistence.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.edfu.core.commons.persistence.api.IResourceMgtPersistence;
import com.edfu.core.commons.persistence.entity.ResourceEntity;
import com.edfu.core.commons.persistence.entity.ResourceMappingEntity;

@Repository
public class ResourceMgtPersistenceImpl implements IResourceMgtPersistence {
	
	private static Logger logger = LoggerFactory.getLogger(ResourceMgtPersistenceImpl.class);
	
	private EntityManager entityManager;
	
//	@Autowired
//	private MongoTemplate mongoTemplate;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@Override
	public ResourceEntity addResource(ResourceEntity re) {
		return entityManager.merge(re);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ResourceEntity getResource(String uuid) {
		logger.debug("Getting Resource for the UUID : " + uuid);
		Query query = entityManager.createQuery("select t from ResourceEntity t where t.uuid = :uuid");
		query.setParameter("uuid", uuid);
		
		List<ResourceEntity> entityList = query.getResultList();
		ResourceEntity re = null;
		if (entityList != null && entityList.size() > 0) {
			re = entityList.get(0);
		}
		
		return re;
	}
	
	public ResourceEntity getResource(long resourceId) {
		return entityManager.find(ResourceEntity.class, resourceId);
	}

	@Override
	public ResourceMappingEntity mapResource(long resourceId, long objectId, String objectType) {
		ResourceMappingEntity rme = new ResourceMappingEntity();
		rme.setObjectId(objectId);
		rme.setObjectType(objectType);
		rme.setResource(getResource(resourceId));
		
		return entityManager.merge(rme);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ResourceMappingEntity> getParents(ResourceEntity resourceEntity) {
		Query query = entityManager.createQuery("select r from ResourceMappingEntity r where r.resource = :resource");
		query.setParameter("resource", resourceEntity);
		
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ResourceMappingEntity> getResourceMappings(long objectId, String objectType) {
		Query query = entityManager.createQuery("select r from ResourceMappingEntity r where r.objectId = :objectId and r.objectType = :objectType");
		query.setParameter("objectId", objectId);
		query.setParameter("objectType", objectType);
		
		return query.getResultList();
	}

	@Override
	public void deleteResource(String uuid) {
		Query query = entityManager.createQuery("delete from ResourceEntity r where r.uuid = :uuid");
		query.setParameter("uuid", uuid).executeUpdate();
	}	

}
